class LoadFiles {
    static getLoadFilesIns() {
        return new LoadFiles();
    }
    constructor() {
        this.root = document.head;
        this.task = [];
    }
    // files 标准格式为 [ { link:'文件链接', text: '文字部分', tag: '这里额外的部分可以用来做其他事情' } ]
    addFile(files) {
        if (typeof files === "string") {
            files = [{link: files}];
        }
        if (files instanceof Array) {} else {
            if (typeof files === "object") {
                files = [files];
            } else {
                throw new Error("files 只能是字符串或数组");
            }
        }
        files.forEach(fileObj => {
            let file = fileObj.link;
            if (file.split('?')[0].endsWith('.js')) {
                this.task.push(this._insertJSFile.bind(this,fileObj));
            } else if (file.split('?')[0].endsWith('.css')) {
                this.task.push(this._insertCSSFile.bind(this,fileObj));
            }
        });
        return this;
    }
    load(callback) {
        // let $this = this;
        let doIt = () => {
            let allTask = this.task.length;
            if (this.task.length) {
                this.task.shift()(callback).then(link => {
                    callback({
                        file: link,
                        task: this.task.length,
                        allTask,
                        over: false,
                        next: doIt
                    });
                    // doIt();
                });
            } else {
                setTimeout(() => {
                    callback({
                        over: true,
                        next: ()=>{}
                    })
                },200);
            }
        }
        setTimeout(function () {
            doIt();
        });
    }

    _insertDomToHead(domType,doFn,onload) {
        return new Promise(function (s) {
            let dom = document.createElement(domType);
            let link = doFn(dom);
            document.head.append(dom);
            if (onload) {
                dom.onload = function () {
                    s(link);
                }
            } else {
                s(link);
            }
        })
    }
    _insertJSFile(link,cb) {
        cb({
            file: link,
            start: true,
        });
        return this._insertDomToHead('script',function (script) {
            script.src = link.link;
            return link;
        },true);
    }
    _insertCSSFile(link,cb) {
        cb({
            file: link,
            start: true,
        });
        return this._insertDomToHead('link',function (dom) {
            dom.setAttribute('rel','stylesheet');
            dom.href = link.link;
            return link;
        },false);
    }
}
